<template>
  <view class="order-list-page">
    <!-- 页面头部 -->
    <!-- <view class="page-header">
      <view class="header-left" @click="goBack">
        <view class="back-icon"></view>
      </view>
      <view class="header-title">{{ getStatusTitle(status) }}</view>
      <view class="header-right"></view>
    </view> -->

    <!-- 订单列表区域 -->
    <view class="order-list-container">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 错误状态 -->
      <view v-else-if="error" class="error-container">
        <view class="error-icon">!</view>
        <text class="error-text">{{ error }}</text>
        <button class="retry-btn" @click="fetchOrders">重新加载</button>
      </view>

      <!-- 空状态 -->
      <view v-else-if="orders.length === 0" class="empty-container">
        <view class="empty-icon">
          <image src="/common/images/empty-order.png" alt="暂无订单" class="empty-image" />
        </view>
        <text class="empty-text">暂无订单</text>
        <button class="go-shopping-btn" @click="goHome">去逛逛</button>
      </view>

      <!-- 订单列表 -->
      <view v-else class="orders-wrapper">
        <view v-for="order in orders" :key="order.orderId" class="order-card">
          <!-- 订单头部 -->
          <view class="order-header">
            <view class="order-info">
              <text class="order-time">{{ formatDate(order.createdAt) }}</text>
              <text class="order-number">订单号: {{ order.orderId }}</text>
            </view>
            <text class="order-status" :class="getStatusClass(order.status)">{{ formatStatus(order.status) }}</text>
          </view>

          <!-- 订单内容 -->
          <view class="order-content">
            <view v-if="order.orderTickets && order.orderTickets.length > 0" class="ticket-list">
              <view v-for="ticket in order.orderTickets" :key="ticket.orderTicketId" class="ticket-item">
                <view class="ticket-info">
                  <text class="ticket-name">{{ getTicketTypeName(ticket.ticket?.ticketType) }}</text>
                  <text class="ticket-price">¥{{ ticket.unitPrice }} × {{ ticket.quantity }}</text>
                </view>
                <text v-if="ticket.ticket?.desc" class="ticket-desc">{{ truncateText(ticket.ticket.desc, 30) }}</text>
              </view>
            </view>
            <view v-else class="no-tickets">
              <text class="no-tickets-text">暂无票务信息</text>
            </view>
          </view>

          <!-- 订单底部 -->
          <view class="order-footer">
            <view class="order-total">
              <text class="total-label">共{{ getTotalQuantity(order) }}件商品</text>
              <text class="total-price">合计: ¥{{ order.totalPrice }}</text>
            </view>
            <view class="action-buttons">
              <button v-if="order.status === 'pending'" class="action-btn cancel-btn" @click="cancelOrder(order.orderId)">取消订单</button>
              <button v-if="order.status === 'pending'" class="action-btn pay-btn" @click="payOrder(order.orderId)">去支付</button>
              <button v-if="order.status === 'paid'" class="action-btn use-btn" @click="useTicket(order.orderId)">去使用</button>
              <button v-if="order.status === 'paid'" class="action-btn refund-btn" @click="refundOrder(order.orderId)">申请退款</button>
              <button v-if="order.status === 'completed'" class="action-btn comment-btn" @click="commentOrder(order.orderId)">去评价</button>
              <button class="action-btn detail-btn" @click="viewOrderDetail(order.orderId)">订单详情</button>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="canLoadMore" class="load-more-container">
          <view class="load-more" @click="loadMoreOrders">
            <text class="load-more-text">加载更多</text>
            <view class="load-more-icon"></view>
          </view>
        </view>

        <!-- 没有更多 -->
        <view v-else-if="orders.length > 0" class="no-more">
          <text class="no-more-text">没有更多了</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { orderApi } from '@/common/api/order.js'

// 响应式数据
const orders = ref([])
const loading = ref(false)
const error = ref('')
const status = ref('')
const currentPage = ref(1)
const total = ref(0)
const pageSize = ref(10)
const canLoadMore = ref(true)

// 从URL参数获取状态
onLoad(async (options) => {
  status.value = options.status || ''
  await fetchOrders()
})

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  error.value = ''
  currentPage.value = 1
  orders.value = []
  canLoadMore.value = true
  
  try {
    // 获取本地存储的用户ID
    const storedUserInfo = uni.getStorageSync('userInfo')
    const userId = storedUserInfo ? (storedUserInfo.userId || storedUserInfo.id || storedUserInfo.user_id) : ''
    
    // 构建请求参数
    const params = {
      status: status.value,
      userId,
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    const res = await orderApi.getUserOrdersByStatus(params)
    
    if (res.code === 200) {
      orders.value = res.data.list || []
      total.value = res.data.total || 0
      
      // 判断是否还有更多数据
      canLoadMore.value = orders.value.length < total.value
    } else {
      error.value = res.message || '获取订单失败'
    }
  } catch (err) {
    console.error('获取订单失败:', err)
    error.value = '网络错误，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 加载更多订单
const loadMoreOrders = async () => {
  if (loading.value || !canLoadMore.value) return
  
  loading.value = true
  currentPage.value++
  
  try {
    const storedUserInfo = uni.getStorageSync('userInfo')
    const userId = storedUserInfo ? (storedUserInfo.userId || storedUserInfo.id || storedUserInfo.user_id) : ''
    
    const params = {
      status: status.value,
      userId,
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    const res = await orderApi.getUserOrdersByStatus(params)
    
    if (res.code === 200 && res.data.list && res.data.list.length > 0) {
      orders.value = [...orders.value, ...res.data.list]
      
      // 判断是否还有更多数据
      canLoadMore.value = orders.value.length < (res.data.total || total.value)
    } else {
      canLoadMore.value = false
    }
  } catch (err) {
    console.error('加载更多订单失败:', err)
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 跳转到首页
const goHome = () => {
  uni.switchTab({ url: '/pages/index/index' })
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  uni.navigateTo({ url: `/pages/orders/detail?id=${orderId}` })
}

// 取消订单
const cancelOrder = (orderId) => {
  uni.showModal({
    title: '取消订单',
    content: '确定要取消该订单吗？',
    success: (res) => {
      if (res.confirm) {
        // 调用取消订单接口
        console.log('取消订单:', orderId)
        orderApi.cancelOrder(orderId).then(res => {
          if (res.code === 200) {
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            })
            // 取消后刷新订单列表
            fetchOrders()
          } else {
            uni.showToast({
              title: res.message || '取消订单失败',
              icon: 'none'
            })
          }
        })  
      }
    }
  })
}

// 支付订单
const payOrder = (orderId) => {
  console.log('支付订单:', orderId)
  // 跳转到支付宝支付页面
  uni.navigateTo({ url: `/pages/orders/alipay?orderId=${orderId}` })
}

// 使用门票
const useTicket = (orderId) => {
  console.log('使用门票:', orderId)
  // 跳转到电子票详情页面
  uni.navigateTo({ url: `/pages/orders/ticket-detail?orderId=${orderId}` })
}

// 申请退款
const refundOrder = (orderId) => {
  console.log('申请退款:', orderId)
  // 跳转到退款页面
  uni.navigateTo({ url: `/pages/orders/refund?id=${orderId}` })
}

// 评价订单
const commentOrder = (orderId) => {
  console.log('评价订单:', orderId)
  // 跳转到评价页面
  uni.navigateTo({ url: `/pages/orders/comment?id=${orderId}` })
}

// 工具函数

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    'pending': '待支付',
    'paid': '已支付',
    'comment': '待评价',
    'completed': '已完成',
    'canceled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 获取状态对应的类名
const getStatusClass = (status) => {
  return `status-${status}`
}

// 获取状态标题
const getStatusTitle = (status) => {
  const titleMap = {
    'pending': '待付款',
    'paid': '待使用',
    'comment': '待评价',
    'canceled': '退款售后'
  }
  return titleMap[status] || '全部订单'
}

// 获取票类型名称
const getTicketTypeName = (type) => {
  const typeMap = {
    'adult': '成人票',
    'child': '儿童票',
    'student': '学生票',
    'senior': '老人票',
    'group': '团购票'
  }
  return typeMap[type] || type || '门票'
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text || text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 获取订单中所有票的总数量
const getTotalQuantity = (order) => {
  if (!order.orderTickets || order.orderTickets.length === 0) return 0
  return order.orderTickets.reduce((total, ticket) => total + ticket.quantity, 0)
}
</script>

<style lang="scss" scoped>
// 使用主题色
$brand-theme-color: #98c3fd;
$primary-text: #333333;
$secondary-text: #666666;
$tertiary-text: #999999;
$background-color: #f8f8f8;
$card-background: #ffffff;
$border-color: #eeeeee;
$success-color: #52c41a;
$warning-color: #faad14;
$danger-color: #ff4d4f;

.order-list-page {
  min-height: 100vh;
  background-color: $background-color;

  // 页面头部
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100rpx;
    padding: 0 30rpx;
    background-color: $card-background;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .header-left,
    .header-right {
      width: 80rpx;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .header-left {
      justify-content: flex-start;
    }

    .header-right {
      justify-content: flex-end;
    }

    .back-icon {
      width: 32rpx;
      height: 32rpx;
      border-left: 4rpx solid $primary-text;
      border-bottom: 4rpx solid $primary-text;
      transform: rotate(45deg);
    }

    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: $primary-text;
      flex: 1;
      text-align: center;
    }
  }

  // 订单列表容器
  .order-list-container {
    padding: 20rpx;

    // 加载状态
    .loading-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 100rpx 0;

      .loading-spinner {
        width: 60rpx;
        height: 60rpx;
        border: 6rpx solid rgba(152, 195, 253, 0.3);
        border-top-color: $brand-theme-color;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }

      .loading-text {
        margin-top: 20rpx;
        font-size: 28rpx;
        color: $tertiary-text;
      }
    }

    // 错误状态
    .error-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 100rpx 0;

      .error-icon {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        background-color: rgba(255, 77, 79, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 60rpx;
        color: $danger-color;
        margin-bottom: 20rpx;
      }

      .error-text {
        font-size: 30rpx;
        color: $secondary-text;
        margin-bottom: 40rpx;
      }

      .retry-btn {
        background-color: $brand-theme-color;
        color: white;
        border-radius: 40rpx;
        padding: 0 60rpx;
        font-size: 28rpx;
      }
    }

    // 空状态
    .empty-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 20rpx;
      padding: 150rpx 0;

      .empty-icon {
        width: 120rpx;
        height: 120rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        .empty-image{
          width: 100%;
          height: 100%;
        }

      }

      .empty-text {
        font-size: 30rpx;
        color: $tertiary-text;
      }

      .go-shopping-btn {
        background-color: $brand-theme-color;
        color: white;
        border-radius: 40rpx;
        padding: 0 60rpx;
        font-size: 28rpx;
      }
    }

    // 订单列表包装器
    .orders-wrapper {
      .order-card {
        background-color: $card-background;
        border-radius: 20rpx;
        margin-bottom: 30rpx;
        overflow: hidden;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

        // 订单头部
        .order-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 30rpx;
          border-bottom: 1rpx solid $border-color;

          .order-info {
            flex: 1;

            .order-time {
              display: block;
              font-size: 28rpx;
              color: $tertiary-text;
              margin-bottom: 8rpx;
            }

            .order-number {
              display: block;
              font-size: 26rpx;
              color: $tertiary-text;
            }
          }

          .order-status {
            font-size: 30rpx;
            font-weight: 600;
          }

          .status-pending {
            color: $warning-color;
          }

          .status-paid {
            color: $brand-theme-color;
          }

          .status-completed {
            color: $success-color;
          }

          .status-canceled,
          .status-refunded {
            color: $tertiary-text;
          }
        }

        // 订单内容
        .order-content {
          padding: 30rpx;
          border-bottom: 1rpx solid $border-color;

          .ticket-list {
            .ticket-item {
              padding: 20rpx 0;
              border-bottom: 1rpx solid $border-color;

              &:last-child {
                border-bottom: none;
                padding-bottom: 0;
              }

              .ticket-info {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 10rpx;

                .ticket-name {
                  font-size: 32rpx;
                  color: $primary-text;
                  font-weight: 500;
                  flex: 1;
                }

                .ticket-price {
                  font-size: 32rpx;
                  color: $danger-color;
                  font-weight: 600;
                }
              }

              .ticket-desc {
                font-size: 26rpx;
                color: $tertiary-text;
                line-height: 38rpx;
              }
            }
          }

          .no-tickets {
            text-align: center;
            padding: 40rpx 0;

            .no-tickets-text {
              font-size: 28rpx;
              color: $tertiary-text;
            }
          }
        }

        // 订单底部
        .order-footer {
          padding: 30rpx;

          .order-total {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30rpx;

            .total-label {
              font-size: 28rpx;
              color: $secondary-text;
            }

            .total-price {
              font-size: 34rpx;
              color: $danger-color;
              font-weight: 600;
            }
          }

          .action-buttons {
            display: flex;
            justify-content: flex-end;
            flex-wrap: wrap;
            gap: 20rpx;

            .action-btn {
              font-size: 26rpx;
              padding: 16rpx 36rpx;
              border-radius: 30rpx;
              line-height: 1;
            }

            .pay-btn {
              background-color: $danger-color;
              color: white;
              border: none;
            }

            .use-btn {
              background-color: $brand-theme-color;
              color: white;
              border: none;
            }

            .cancel-btn,
            .refund-btn,
            .comment-btn,
            .detail-btn {
              background-color: white;
              color: $secondary-text;
              border: 1rpx solid $border-color;
            }
          }
        }
      }

      // 加载更多
      .load-more-container {
        margin-top: 30rpx;

        .load-more {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 30rpx;
          background-color: $card-background;
          border-radius: 20rpx;
          
          .load-more-text {
            font-size: 28rpx;
            color: $secondary-text;
            margin-right: 10rpx;
          }
          
          .load-more-icon {
            width: 20rpx;
            height: 20rpx;
            border-right: 3rpx solid $tertiary-text;
            border-bottom: 3rpx solid $tertiary-text;
            transform: rotate(45deg);
          }
        }
      }

      // 没有更多
      .no-more {
        text-align: center;
        padding: 40rpx 0;
        
        .no-more-text {
          font-size: 26rpx;
          color: $tertiary-text;
        }
      }
    }
  }
}

// 动画
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
